package pers.xiaoliang.concurrency.example.count;

import pers.xiaoliang.concurrency.annotation.ThreadSafe;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @version v1.0
 * @description: 计数器例子1 - 使用Atomicxxx
 * @author: xiaoliang.liu
 * @date: 2018/7/26 21:31
 */
@ThreadSafe
public class CountExample1 {
    /**
     * 线程数量(模拟并发数)
     */
    private static int threadTotal = 200;
    /**
     * 请求次数
     */
    private static int clientTotal = 5000;

    private static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {
        // 获得线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 信号量
        final Semaphore semaphore = new Semaphore(threadTotal);

        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println(e);
                }
            });
        }

        // 关闭线程池
        executorService.shutdown();
        System.out.println(count.get());
    }

    private static void add() {
        count.incrementAndGet();
    }
}
